#include <stdio.h>
#include <string.h>
#include <stdlib.h>
// 假设您的 sdf.h 文件在包含路径中
#include "sdf.h" 

// 错误处理宏
#define SDR_CHECK(rv, msg) \
    if (SDR_OK != (rv)) { \
        printf("Error: %s failed, result: 0x%08X\n", (msg), (rv)); \
        goto END_OF_FUN; \
    }

int main(int argc, char *argv[])
{
    SGD_RV rv = SDR_OK;
    SGD_HANDLE phDeviceHandle = NULL;
    SGD_HANDLE phSessionHandle = NULL; // 必须先开会话才能做密码运算
    
    SGD_UCHAR pucRandomData[16] = {0}; // 16字节随机数
    SGD_UINT32 ulRandomLen = 16;
    int i = 0;
    
    printf("--- 开始执行：SDF生成随机数功能测试 (V2) ---\n");

    // --- 1. 连接设备/打开设备 (SDF_OpenDevice) ---
    rv = SDF_OpenDevice(&phDeviceHandle);
    SDR_CHECK(rv, "SDF_OpenDevice");
    printf("1. 成功连接设备，句柄: %p\n", phDeviceHandle);

    // --- 2. 打开会话 (SDF_OpenSession) ---
    // 几乎所有密码运算都需要一个会话句柄
    rv = SDF_OpenSession(phDeviceHandle, &phSessionHandle);
    SDR_CHECK(rv, "SDF_OpenSession");
    printf("2. 成功打开会话，句柄: %p\n", phSessionHandle);
    
    // --- 3. 核心功能：生成随机数 (SDF_GenerateRandom) ---
    rv = SDF_GenerateRandom(phSessionHandle, pucRandomData, ulRandomLen);
    SDR_CHECK(rv, "SDF_GenerateRandom");
    
    printf("3. 成功生成随机数 (%u bytes):\n", ulRandomLen);
    printf("   -> 随机数数据: ");
    for(i = 0; i < ulRandomLen; i++)
    {
        printf("%02X", pucRandomData[i]);
    }
    printf("\n");
    
    
END_OF_FUN:
    
    printf("\n--- 清理资源 ---\n");
    
    // --- 4. 关闭会话 ---
    if(phSessionHandle) {
        SDF_CloseSession(phSessionHandle);
        printf("4. 成功关闭会话\n");
    }

    // --- 5. 关闭设备 ---
    if(phDeviceHandle) {
        SDF_CloseDevice(phDeviceHandle);
        printf("5. 成功关闭设备\n");
    }
    
    if(rv == SDR_OK) {
        printf("\n--- 功能执行成功！---\n");
    } else {
        printf("\n--- 功能执行失败，错误码: 0x%08X ---\n", rv);
    }
        
    return 1;
}
